package com.bawei.module_video.ui

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.mvi.base.BaseMVIFragment
import com.bawei.lib_common.utils.ScrollConflictUtils
import com.bawei.lib_common.utils.UserUtils
import com.bawei.lib_storage.room.FavoriteManager
import com.bawei.module_video.R
import com.bawei.module_video.adapter.VideoAdapter
import com.bawei.module_video.adapter.VideoSortAdapter
import com.bawei.module_video.databinding.FragmentVideoBinding
import com.bawei.module_video.home.intent.SimpleTypeIntent
import com.bawei.module_video.home.state.SimpleTypeState
import com.bawei.module_video.home.state.VideoState
import com.bawei.module_video.home.viewmodel.HomeViewModel
import com.gongwen.marqueen.MarqueeFactory
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import com.google.gson.Gson
import kotlinx.coroutines.launch


class VideoFragment : BaseMVIFragment() {
    private lateinit var homeViewModel: HomeViewModel
    private val binding: FragmentVideoBinding by lazy {
        FragmentVideoBinding.inflate(layoutInflater)
    }
    private lateinit var scrollHandler: Handler
    private lateinit var scrollRunnable: Runnable

    lateinit var adapter_sort: VideoSortAdapter
    lateinit var adapter: VideoAdapter

    // 分页相关变量
    private var currentPage = 1
    private val pageSize = 10
    private var isLoading = false
    private var isLastPage = false
    private var currentChannelId = "" // 当前选中的频道ID
    private var allVideos = mutableListOf<com.bawei.module_video.home.model.entity.VideoEntity>()
    private var currentFilterCategory: String? = null
    private var currentFilterSort: String? = null

    override fun generateViewModel() {
        homeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
    }

    override fun lazyLoad() {

    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                homeViewModel.simpleTypeFlow_.collect {
                    when (it) {
                        is SimpleTypeState.Init -> {
                            showMsg("初始化")
                        }

                        is SimpleTypeState.Empty -> {
                            showMsg("空")
                        }

                        is SimpleTypeState.Failed -> {
                            showMsg("失败")
                        }

                        is SimpleTypeState.SimpleTypeSuccess -> {
                            it.list?.let { list ->
                                adapter_sort.setData(list)
                                if (list.isNotEmpty()) {
                                    currentChannelId = list[0].channelid // 默认选中第一个频道
                                    loadData(currentChannelId, 1, true)
                                }
                            }
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                homeViewModel.videoFlow_.collect {
                    when (it) {
                        is VideoState.Init -> {
                            showMsg("初始化")
                        }

                        is VideoState.Empty -> {
                            showMsg("空")
                        }

                        is VideoState.Failed -> {
                            showMsg("失败")
                        }

                        is VideoState.VideoSuccess -> {
                            showMsg("成功")
                            handleLoadComplete()

                            it.list?.let { videoList ->
                                if (currentPage == 1) {
                                    allVideos.clear()
                                    allVideos.addAll(videoList)
                                    adapter.setData(videoList)
                                } else {
                                    allVideos.addAll(videoList)
                                    adapter.addData(videoList)
                                }

                                // 判断是否是最后一页
                                isLastPage = videoList.size < pageSize
                                
                                // 检查收藏状态
                                checkFavoriteStatus(videoList)
                            }
                        }
                    }
                }
            }
        }
    }

    override fun initData() {
        super.initData()
        //发送意图
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel.intents.send(SimpleTypeIntent.getSimpleType)
                homeViewModel.handleIntent()

            }
        }
    }

    override fun initView() {
        super.initView()
        // 初始化分类适配器
        adapter_sort = VideoSortAdapter { channel ->
            currentChannelId = channel
            currentPage = 1
            isLastPage = false
            loadData(channel, currentPage, true)
        }
        binding.rvSort.adapter = adapter_sort
        binding.rvSort.layoutManager = LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false)
        
        // 解决滑动冲突：水平滚动的RecyclerView与父容器的冲突
        ScrollConflictUtils.resolveHorizontalRecyclerViewInScrollView(binding.rvSort)

        // 初始化视频适配器
        adapter = VideoAdapter()
        binding.rv.adapter = adapter
        binding.rv.layoutManager = GridLayoutManager(requireActivity(),2)
        
        // 设置视频点击事件
        adapter.onItemClickListener = { videoEntity ->
            // 跳转到视频详情页面
            navigateToVideoDetail(videoEntity)
        }
        
        // 设置收藏点击事件
        adapter.onFavoriteClickListener = { videoEntity, isFavorite ->
            handleFavoriteClick(videoEntity, isFavorite)
        }

        // 设置下拉刷新
        binding.swipeRefreshLayout.setOnRefreshListener {
            currentPage = 1
            isLastPage = false
            isLoading = false  // 添加这行，确保重置加载状态

            // 2秒后自动停止刷新
            Handler(Looper.getMainLooper()).postDelayed({
                if (binding.swipeRefreshLayout.isRefreshing) {
                    binding.swipeRefreshLayout.isRefreshing = false
                    showMsg("刷新超时")
                    isLoading = false  // 确保超时后重置状态
                }
            }, 2000)

            loadData(currentChannelId, currentPage, true)
        }

        // 设置上拉加载更多
        binding.rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val visibleItemCount = layoutManager.childCount
                val totalItemCount = layoutManager.itemCount
                val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()

                if (!isLoading && !isLastPage) {
                    if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0
                        && totalItemCount >= pageSize) {
                        loadMoreData()
                    }
                }
            }
        })

        //这里用了第三方实现的跑马灯效果
        // 准备数据
        val texts = listOf("热播电影", "今日推荐长歌行", "搜搜你想看的")

// 创建适配器
        val marqueeFactory = object : MarqueeFactory<TextView, String>(requireActivity()) {
            override fun generateMarqueeItemView(data: String): TextView {
                val textView = TextView(context)
                textView.text = data
                textView.textSize = 16f
                textView.setTextColor(Color.BLACK)
                textView.setPadding(0, 16, 0, 16)
                return textView
            }
        }

// 设置数据
        marqueeFactory.setData(texts)
        binding.marqueeView.setMarqueeFactory(marqueeFactory)

// 配置翻页效果
        binding.marqueeView.apply {
            setOnItemClickListener { _, _, position ->
                // 点击事件处理
                Toast.makeText(context, "点击了: ${texts[position]}", Toast.LENGTH_SHORT).show()
            }

            // 设置翻页动画
            setInAndOutAnim(
                R.anim.in_bottom_to_top,  // 进入动画
                R.anim.out_top_to_bottom  // 退出动画
            )

            // 设置停留时间
            setAnimDuration(500L) // 2秒

            // 开始滚动
            startFlipping()
        }

        // 筛选按钮弹窗
        binding.root.findViewById<TextView>(R.id.des).setOnClickListener {
            showFilterDialog()
        }
    }
    
    /**
     * 检查收藏状态
     */
    private fun checkFavoriteStatus(videoList: List<com.bawei.module_video.home.model.entity.VideoEntity>) {
        lifecycleScope.launch {
            try {
                val userId = UserUtils.getCurrentUserId().ifEmpty { UserUtils.getDefaultUserId() }
                
                videoList.forEach { videoEntity ->
                    val isFavorite = FavoriteManager.isFavorite(userId, videoEntity.id.toString())
                    videoEntity.isFavorite = isFavorite
                }
                
                // 刷新适配器
                adapter.notifyDataSetChanged()
                
            } catch (e: Exception) {
                Log.e("VideoFragment", "检查收藏状态失败: ${e.message}", e)
            }
        }
    }
    
    /**
     * 处理收藏点击事件
     */
    private fun handleFavoriteClick(videoEntity: com.bawei.module_video.home.model.entity.VideoEntity, isFavorite: Boolean) {
        lifecycleScope.launch {
            try {
                val userId = UserUtils.getCurrentUserId().ifEmpty { UserUtils.getDefaultUserId() }
                
                if (isFavorite) {
                    // 添加收藏
                    val success = FavoriteManager.addFavorite(
                        userId = userId,
                        videoId = videoEntity.id.toString(),
                        title = videoEntity.title,
                        primaryImg = videoEntity.videomainimag,
                        content = videoEntity.description,
                        authorImg = videoEntity.avatar_url,
                        authorName = videoEntity.name,
                        videoPath = videoEntity.videopath,
                        channelId = videoEntity.channelid
                    )
                    if (success) {
                        showMsg("已收藏")
                    } else {
                        showMsg("收藏失败")
                        // 恢复状态
                        videoEntity.isFavorite = false
                        adapter.notifyDataSetChanged()
                    }
                } else {
                    // 取消收藏
                    val success = FavoriteManager.removeFavorite(userId, videoEntity.id.toString())
                    
                    if (success) {
                        showMsg("已取消收藏")
                    } else {
                        showMsg("取消收藏失败")
                        // 恢复状态
                        videoEntity.isFavorite = true
                        adapter.notifyDataSetChanged()
                    }
                }
                
            } catch (e: Exception) {
                Log.e("VideoFragment", "处理收藏失败: ${e.message}", e)
                showMsg("操作失败")
                // 恢复状态
                videoEntity.isFavorite = !isFavorite
                adapter.notifyDataSetChanged()
            }
        }
    }
    
    /**
     * 跳转到视频详情页面
     */
    private fun navigateToVideoDetail(videoEntity: com.bawei.module_video.home.model.entity.VideoEntity) {
         //这里可以使用ARouter跳转到视频详情页面
        val s = Gson().toJson(videoEntity)
         ARouter.getInstance().build("/detail/DetailActivity")
             .withString("detail", s)
             .navigation()
        
        // 暂时显示提示
        showMsg("跳转到视频详情: ${videoEntity.title}")
    }
    
    private fun loadData(channelId: String, page: Int, isRefresh: Boolean) {
        isLoading = true
        if (isRefresh) {
            binding.swipeRefreshLayout.isRefreshing = true
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                homeViewModel.intents.send(
                    SimpleTypeIntent.getVideoType(
                        channel = channelId,
                        page = page,
                        pageSize = pageSize
                    )
                )
                homeViewModel.handleIntent()
            }
        }
    }
    private fun loadMoreData() {
        if (!isLoading && !isLastPage) {
            isLoading = true
            adapter.setLoading(true)  // 显示加载视图
            currentPage++
            loadData(currentChannelId, currentPage, false)
        }
    }

    private fun handleLoadComplete() {
        isLoading = false
        adapter.setLoading(false)  // 隐藏加载视图
        if (binding.swipeRefreshLayout.isRefreshing) {
            binding.swipeRefreshLayout.isRefreshing = false
        }
    }

    private fun showFilterDialog() {
        if (allVideos.isEmpty()) {
            Toast.makeText(requireContext(), "暂无可筛选数据", Toast.LENGTH_SHORT).show()
            return
        }
        val dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_filter_video, null, false)
        val dialog = BottomSheetDialog(requireContext())
        dialog.setContentView(dialogView)

        val categories = allVideos.map { it.channelid }.distinct().filter { it.isNotBlank() }
        val chipGroupCategory = dialogView.findViewById<ChipGroup>(R.id.chipGroupCategory)
        chipGroupCategory.removeAllViews()
        categories.forEach { cat ->
            val chip = Chip(requireContext())
            chip.text = cat
            chip.isCheckable = true
            chipGroupCategory.addView(chip)
        }

        val sorts = listOf("最新", "最热", "最多评论")
        val chipGroupSort = dialogView.findViewById<ChipGroup>(R.id.chipGroupSort)
        chipGroupSort.removeAllViews()
        sorts.forEach { sort ->
            val chip = Chip(requireContext())
            chip.text = sort
            chip.isCheckable = true
            chipGroupSort.addView(chip)
        }

        dialogView.findViewById<View>(R.id.chipGroupDuration)?.visibility = View.GONE
        dialogView.findViewById<View>(R.id.chipGroupDuration)?.parent?.let {
            if (it is View) it.visibility = View.GONE
        }

        dialogView.findViewById<View>(R.id.btnClear).setOnClickListener {
            chipGroupCategory.clearCheck()
            chipGroupSort.clearCheck()
        }
        dialogView.findViewById<View>(R.id.btnConfirm).setOnClickListener {
            val selectedCategoryChip = chipGroupCategory.checkedChipIds.firstOrNull()?.let { chipGroupCategory.findViewById<Chip>(it) }
            val selectedCategory = selectedCategoryChip?.text?.toString()
            val selectedSortChip = chipGroupSort.checkedChipIds.firstOrNull()?.let { chipGroupSort.findViewById<Chip>(it) }
            val selectedSort = selectedSortChip?.text?.toString()
            currentFilterCategory = selectedCategory
            currentFilterSort = selectedSort
            applyFilter()
            dialog.dismiss()
        }
        dialog.show()
    }

    private fun applyFilter() {
        var filtered = allVideos.toList()
        // 分类筛选
        currentFilterCategory?.let { cat ->
            filtered = filtered.filter { it.channelid == cat }
        }
        // 排序
        filtered = when (currentFilterSort) {
            "最新" -> filtered.sortedByDescending { it.ctime }
            "最热" -> filtered.sortedByDescending { it.playnum }
            "最多评论" -> filtered.sortedByDescending { it.commentnum }
            else -> filtered
        }
        adapter.setData(filtered)
    }

}
